package com.toppitch.site.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map.Entry;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.toppitch.site.config.AppConfig;
import com.toppitch.site.config.ContentMapping;
import com.toppitch.site.data.JsonData;
import com.toppitch.site.data.Model;
import com.toppitch.site.db.DBManager;

@Controller
@RequestMapping("/")
public class ModelController extends BaseController {

	@Autowired
	private AppConfig appConfig = null;

	@Autowired
	private ContentMapping contentMapping = null;

	@Autowired
	private DBManager dbmanager;

	@PostConstruct
	public void init() {
		File f = new File(appConfig.getRoot() + appConfig.getMap().get("MODEL_UPDATELOAD_PATH"));
		if (!f.exists()) {
			f.mkdirs();
		}
	}

	@RequestMapping("modelupload")
	public String putModel(MultipartHttpServletRequest request, ModelMap model) {
		JsonData jsonData = new JsonData();
		jsonData.setSucceed(true);
		for (Entry<String, MultipartFile> entry : request.getFileMap()
				.entrySet()) {
			MultipartFile file = entry.getValue();
			if ("".equals(file.getOriginalFilename())) {
				continue;
			}
			Model m = new Model();
			m.setModelId(System.currentTimeMillis() + "");
			m.setModelFileName(file.getOriginalFilename());

			File f = new File(appConfig.getRoot() + appConfig.getMap().get("MODEL_UPDATELOAD_PATH")
					+ m.getModelId());
			try {
				file.transferTo(f);
				dbmanager.execute(m.toInsertString());
				jsonData.setSuccessMessage("" + m.getModelId());
				jsonData.setBindKey(m.getModelFileName());
			} catch (IOException e) {
				e.printStackTrace();
				jsonData.setSucceed(false);
				jsonData.setErrorMessage("Cannot read model file.");
			}
		}
		model.addAttribute("jsonData", jsonData);

		return "filejson";
	}

	@RequestMapping("model/{modelId}/{modelFileName}")
	public String getModel(//
			@PathVariable("modelId") String modelId, //
			@PathVariable("modelFileName") String modelFileName, //
			HttpServletResponse response) {
		if (modelFileName.contains(".")) {
			String type = modelFileName.substring(
					modelFileName.lastIndexOf('.')).toLowerCase();
			if (contentMapping.getMap().containsKey(type)) {
				response.setContentType(contentMapping.getMap().get(type));
			}
		}

		File f = new File(appConfig.getRoot() + appConfig.getMap().get("MODEL_UPDATELOAD_PATH")
				+ modelId);
		if (f.exists() && f.canRead()) {
			InputStream is = null;
			try {
				is = new FileInputStream(f);
				byte[] b = new byte[1024];
				int len = -1;
				while ((len = is.read(b)) > 0) {
					response.getOutputStream().write(b, 0, len);
				}
				response.getOutputStream().flush();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				try {
					response.getOutputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return "dummy";
	}
}
